package com.zsjt.app.controller;


import com.zsjt.app.pojo.UserDto;
import com.zsjt.app.service.SendCodeService;
import com.zsjt.app.service.UserDtoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserDtoController {

    private UserDtoService userDtoService;

    private SendCodeService sendCodeService;

    @Autowired
    @Qualifier("sendCodeService")
    public void setSendCodeService(SendCodeService sendCodeService) {
        this.sendCodeService = sendCodeService;
    }

    @Autowired
    @Qualifier("userDtoService")
    public void setUserDtoService(UserDtoService userDtoService) {
        this.userDtoService = userDtoService;
    }


    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping("/main")
    public String main(Authentication authentication, HttpSession session){
        UserDto userDto = userDtoService.findUserByAccount(authentication.getName());
        session.setAttribute("user",userDto);
/*        System.out.println(userDto);*/
        return "index/main";
    }

    /**
     * 检验用户账户是否已经存在
     * @param user_account
     * @return
     */
    @RequestMapping(value = "/userIsAccountExist",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserIsAccountExist(String user_account){
        UserDto user = userDtoService.findUserByAccount(user_account);
        boolean isExist = false;
        if(user!=null) {
            isExist = true;
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("isExist", isExist);
        map.put("user", user);
        map.put("errorMes","该账号不存在！");
        map.put("successMes","");
        return map;
    }

    /**
     *发送邮箱验证码
     * @param user_email
     * @return
     */
    @RequestMapping(value = "/userSendEmailCode",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserSendEmailCode(String user_email){
        Map<String,Object> map = new HashMap<>();
        boolean isOK = false;
        String code = sendCodeService.sendEmailCode(user_email);
       // String code = "abcdedf";
        if(code !=null ||code.length()>0){
            isOK = true;
        }
        map.put("isOK",isOK);
        map.put("code",code);
        map.put("successMes","邮箱验证码已发送");
        map.put("errorMes","邮箱验证码发送失败");
        return map;
    }

    /**
     * 发送手机验证码
     * @param user_phone
     * @return
     */
    @RequestMapping(value = "/userSendPhoneCode",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserSendPhoneCode(String user_phone){
        Map<String,Object> map = new HashMap<>();
        boolean isOK = false;
        String code = sendCodeService.sendPhoneCode(user_phone);
        if(code !=null ||code.length()>0){
            isOK = true;
        }
        map.put("isOK",isOK);
        map.put("code",code);
        map.put("successMes","短信验证码已发送");
        map.put("errorMes","短信验证码发送失败");
        return map;
    }


    /**
     * 检验用户邮箱是否存在
     * @param user_email
     * @return
     */
    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping(value = "/userIsEmailExist",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserIsEmailExist(String user_email){
        Map map = new HashMap();
        boolean isExist = false;
        if(userDtoService.isEmailExist(user_email)==true){
            isExist = true;
        }
        map.put("successMes","该邮箱可以注册！");
        map.put("errorMes","该邮箱已被注册！");
        map.put("isExist",isExist);
        return map;
    }

    /**
     * 检验用户手机号码是否存在
     * @param user_phone
     * @param mode
     * @return
     */
    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping(value = "/userIsPhoneExist",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserIsPhoneExist(String user_phone , String mode){
        Map map = new HashMap();
        boolean isExist = false;
        if(true == userDtoService.isPhoneExist(user_phone)) {
            isExist = true;
        }
        if(mode.equals("login")) {
            map.put("errorMes","该手机号未注册！");
            map.put("successMes","");
        }else {
            map.put("errorMes","该手机号已被注册！");
            map.put("successMes","该手机号可以注册！");
        }
        map.put("isExist",isExist);
        return map;
    }

    /**
     * 用户更新邮箱
     * @param mode
     * @param user_email
     * @return
     */
    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping(value = "/userUpdateEmail",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserUpdateEmail(String mode, String user_email, HttpServletRequest request){
        HttpSession session = request.getSession();
        UserDto user = (UserDto)session.getAttribute("user");
        boolean isOK = false;
        Map<String,Object> map = new HashMap<String,Object>();
        //取消绑定检验是否是唯一验证方式
        if("unbind".equals(mode)) {
            if(!userDtoService.findUserVerify(user.getId())) {
                map.put("errorMes","很抱歉，必须保留一个验证方式，无法取消绑定。\n特殊情况请联系管理员！");
            }else {
                isOK = userDtoService.updateUserEmail(user, mode.equals("bind")?user_email:"");
                map.put("errorMes","很抱歉，遇到了未知错误，可能是服务器出错或网络问题。\n请重试或联系管理员！");
            }
        }else {
            isOK = userDtoService.updateUserEmail(user, mode.equals("bind")?user_email:"");
            map.put("errorMes","很抱歉，遇到了未知错误，可能是服务器出错或网络问题。\n请重试或联系管理员！");
        }
        map.put("isOK", isOK);
        map.put("successMes","你已成功"+(mode.equals("bind")?"绑定":"解绑")+"邮箱："+user_email+"\n窗口即将关闭。。。");
        return map;
    }
    /**
     * 更新用户的手机号码
     * @param mode
     * @param user_phone
     * @param session
     * @return
     */
    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping(value = "/userUpdatePhone",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserUpdatePhone(String mode,String user_phone,HttpSession session){
        UserDto user = (UserDto)session.getAttribute("user");
        boolean isOK = false;
        Map<String,Object> map = new HashMap<String,Object>();
        //取消绑定检验是否是唯一验证方式
        if("unbind".equals(mode)) {
            if(!userDtoService.findUserVerify(user.getId())) {
                map.put("errorMes","很抱歉，必须保留一个验证方式，无法取消绑定。\n特殊情况请联系管理员！");
            }else {
                isOK = userDtoService.updateUserPhone(user, mode.equals("bind")?user_phone:"");
                map.put("errorMes","很抱歉，遇到了未知错误，可能是服务器出错或网络问题。\n请重试或联系管理员！");
            }
        }else {
            isOK = userDtoService.updateUserPhone(user, mode.equals("bind")?user_phone:"");
            map.put("errorMes","很抱歉，遇到了未知错误，可能是服务器出错或网络问题。\n请重试或联系管理员！");
        }
        map.put("isOK", isOK);
        map.put("successMes","你已成功"+(mode.equals("bind")?"绑定":"解绑")+"邮箱："+user_phone+"\n窗口即将关闭。。。");
        return map;
    }

    /**
     * 用户更新密码
     * @param user_account
     * @param user_password
     * @return
     */
    @RequestMapping(value = "/userUpdatePassword",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserUpdatePassword(String user_account , String user_password, HttpSession session){
        UserDto user = userDtoService.findUserByAccount(user_account);
        boolean isOK = false;
        isOK = userDtoService.updateUserPassword(user,user_password);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("isOK", isOK);
        map.put("errorMes","很抱歉，遇到了未知错误，可能是服务器出错或网络问题。\n请重试或联系管理员！");
        map.put("successMes","你的密码已修改，请牢记！");
        //设置session并保存sessionid到Cookie
        session.setAttribute("user", user);
        return map;
    }

    /**
     * 用户更新上传头像
     * @param user_id
     * @param dataURL
     * @return
     * @throws IOException
     */
    @PreAuthorize("isAuthenticated()")  //需要认证通过
    @RequestMapping(value = "/userUploadAvatar",method = {RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> UserUploadAvatar(String user_id, String dataURL) throws IOException {
        boolean isOK = false;
        isOK = userDtoService.uploadAvatar(dataURL,user_id);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("isOK", isOK);
        map.put("errorMes","遇到未知问题，请重试或联系管理员！");
        map.put("successMes","头像上传成功！");
        return map;
    }

    /**
     * 检验用户是否在线
     * @param username
     * @param request
     * @param response
     * @return
     */
//    @RequestMapping(value = "/userOnline.do",method = {RequestMethod.POST})
//    @ResponseBody
//    public Map<String,Object> UserOnline(String username ,HttpServletRequest request, HttpServletResponse response){
//        User loginUser = userService.findUserByAccount(username);
//        System.out.println(loginUser);
//        boolean isOnline = false;
//        Map<String,Object> map = new HashMap<String,Object>();
//        HttpSession session = request.getSession();
//        //检测用户是否已在线
//        ServletContext application = session.getServletContext();
//        Map<String,Object> userMap = application.getAttribute("userMap")==null?new HashMap<String,Object>():
//                (Map<String,Object>)application.getAttribute("userMap");
//        for (String key : userMap.keySet()) {
//            User user = (User)userMap.get(key);
//            if(user.getAccount().equals(loginUser.getAccount())&&!key.equals(session.getId())) {
//                isOnline = true;
//                System.out.println(loginUser.getAccount()+"用户已经在线");
//                break;
//            }
//        }
//        map.put("isOnline", isOnline);
//        map.put("errorMes","您的账号已在其他客户端登录！\n如果不是您本人登录请尽快修改密码！\n强制登录即可强制下线其他客户端的账号");
//        map.put("successMes","");
//        return map;
//    }
}
